package com.kklsqm.langchain4j.config;

import cn.hutool.core.util.HexUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kklsqm.langchain4j.dto.TTSResponseDTO;
import com.kklsqm.langchain4j.dto.VoiceRequestDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能: MiniMax TTS 客户端
 * 作者: 沙琪马
 * 日期: 2025/4/23 11:11
 */
@Component
public class MiniMaxTTSClient {

    @Value("${minimax.api.key}")
    private String apiKey;

    @Value("${minimax.tts.url}")
    private String ttsUrl;

    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

    public byte[] textToSpeech(VoiceRequestDTO request) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiKey);

        HttpEntity<Map<String, Object>> entity = getMapHttpEntity(request, headers);

        ResponseEntity<String> response = restTemplate.exchange(
                ttsUrl,
                HttpMethod.POST,
                entity,
                String.class
        );

        try {
            TTSResponseDTO ttsResponse = objectMapper.readValue(response.getBody(), TTSResponseDTO.class);
            
            // 检查响应状态
            if (ttsResponse.getBase_resp().getStatus_code() != 0) {
                throw new RuntimeException("TTS 请求失败: " + ttsResponse.getBase_resp().getStatus_msg());
            }
            
            // 返回解码后的音频数据
            return HexUtil.decodeHex(ttsResponse.getData().getAudio());
        } catch (IOException e) {
            throw new RuntimeException("解析响应失败", e);
        }
    }

    private static HttpEntity<Map<String, Object>> getMapHttpEntity(VoiceRequestDTO request, HttpHeaders headers) {
        Map<String, Object> body = new HashMap<>();
        body.put("text", request.getText());
        body.put("model", request.getModel());
        body.put("language_boost", request.getLanguage_boost());

        Map<String, Object> voiceSetting = new HashMap<>();
        voiceSetting.put("voice_id", request.getVoice_setting().getVoice_id());
        voiceSetting.put("speed", request.getVoice_setting().getSpeed());
        voiceSetting.put("vol", request.getVoice_setting().getVol());
        voiceSetting.put("pitch", request.getVoice_setting().getPitch());
        voiceSetting.put("emotion", request.getVoice_setting().getEmotion());

        body.put("voice_setting", voiceSetting);

        return new HttpEntity<>(body, headers);
    }

    /**
     * 将十六进制字符串转换为字节数组
     * @param hexString
     * @return
     */
    private byte[] hexStringToByteArray(String hexString) {
        int length = hexString.length();
        byte[] byteArray = new byte[length / 2];
        for (int i = 0; i < length; i += 2) {
            byteArray[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i + 1), 16));
        }
        return byteArray;
    }
}
